//
//  WXPayRequestHandle.m
//  sensen_ios
//
//  Created by pro on 16/4/19.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "WXPayRequestHandle.h"
#import "ZKCryptionHandle.h"
@implementation WXPayRequestHandle

+ (NSString *)getRandomString {
    long r = random();
    
    return [NSString stringWithFormat:@"%ld", r];
}

+ (NSString *)signWithPayDic:(NSDictionary *)dic {
    
    /*
     第一步，设所有发送或者接收到的数据为集合M，将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA。
     特别注意以下重要规则：
     ◆ 参数名ASCII码从小到大排序（字典序）；
     ◆ 如果参数的值为空不参与签名；
     ◆ 参数名区分大小写；
     ◆ 验证调用返回或微信主动通知签名时，传送的sign参数不参与签名，将生成的签名与该sign值作校验。
     ◆ 微信接口可能增加字段，验证签名时必须支持增加的扩展字段
     */
    NSArray *tmp = [dic allKeys];
    NSMutableArray *keys = [NSMutableArray arrayWithArray:tmp];
    for (NSString *key in keys) {
        if ([dic valueForKey:key] == nil || [[dic valueForKey:key] isEqualToString:@""]) {
            [keys removeObject:key];
        }
    }
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:descriptor];
    // 获得排序后的数组
    NSArray *sortKeys = [keys sortedArrayUsingDescriptors:descriptors];
    
    NSMutableString *stringA = [[NSMutableString alloc] init];
    for (NSString *key in sortKeys) {
        NSString *value = [dic valueForKey:key];
        [stringA appendFormat:@"%@=%@&", key, value];
    }
    [stringA deleteCharactersInRange:NSMakeRange(stringA.length - 1, 1)];
    
    /*
     第二步，在stringA最后拼接上key得到stringSignTemp字符串，并对stringSignTemp进行MD5运算，再将得到的字符串所有字符转换为大写，得到sign值signValue。
     key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
     */
    
    NSString *key = @"192006250b4c09247ec02edce69f6a2d";
    NSString *stringSignTemp = [NSString stringWithFormat:@"%@&key=%@", stringA,key];
    NSString *signValue = [[ZKCryptionHandle md5:stringSignTemp] uppercaseString];
    
    return signValue;
}


// 统一支付
+ (void)unifiedorderRequest:(NSDictionary *)params
                    Success:(void(^)(id successResult))success
                    failure:(void(^)(id failureResult))failure {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 默认超时时间10秒
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    [manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder"
       parameters:params
          success:^(AFHTTPRequestOperation *operation ,id responseObject){
              
              DLog(@"预支付返回信息：%@", responseObject);
              
              if ([responseObject isKindOfClass:[NSDictionary class]]) {
                  NSDictionary *dic = (NSDictionary *)responseObject;
                  NSString *return_code = dic[@"return_code"];
                  
                  if ([return_code isEqualToString:@"SUCCESS"]) {
                      
                      WXPayModel *model = [[WXPayModel alloc] init];
                      model.appid = dic[@"appid"];
                      model.partnerid = dic[@"mch_id"];
                      model.noncestr = dic[@"nonce_str"];
                      model.sign = dic[@"sign"];

                      if (![model.sign isEqualToString:params[@"sign"]]) {
                          DLog(@"签名校验失败");
                          return;
                      }
                      if ([dic[@"result_code"] isEqualToString:@"SUCCESS"]) {
                          model.prepayid = dic[@"prepay_id"];
                          
                          if (success) {
                              success(model);
                          }
                      } else {
                          DLog(@"未获得prepay_id");
                      }
                  } else {
                      DLog(@"获得的状态码是:%@", return_code);
                  }
              }
              
          } failure:^(AFHTTPRequestOperation *operation , NSError *error){
              DLog(@"预支付错误返回信息：%@", operation.responseObject);
          }];

    
}
@end
